<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="userDialogFormRef" status-icon :rules="state.rules" :model="state.ruleForm" size="default"
				label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户名称" prop="account">
							<el-input v-model="state.ruleForm.account" placeholder="请输入账户名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户昵称">
							<el-input v-model="state.ruleForm.username" placeholder="请输入用户昵称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户英文名">
							<el-input v-model="state.ruleForm.englishname" placeholder="请输入用户英文名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="关联角色">
							<el-select @change="roleChange" v-model="state.ruleForm.role_id" placeholder="请选择" clearable
								class="w100">
								<el-option v-for="item in state.roleData" :key="item.id" :label="item.name"
									:value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="部门">
							<el-cascader :options="state.deptData"
								:props="{ checkStrictly: true, value: 'id', label: 'name', children: 'children' }"
								placeholder="请选择部门" clearable class="w100" @change="deptChange"
								v-model="state.ruleForm.department">
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="手机号">
							<el-input v-model="state.ruleForm.phone" placeholder="请输入手机号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="邮箱">
							<el-input v-model="state.ruleForm.email" placeholder="请输入" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="性别">
							<el-select v-model="state.ruleForm.gender" placeholder="请选择" clearable class="w100">
								<el-option label="男" :value="1"></el-option>
								<el-option label="女" :value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户密码" prop="password">
							<el-input v-model="state.ruleForm.password" placeholder="请输入" type="password"
								clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户状态">
							<el-switch v-model="state.ruleForm.status" inline-prompt active-text="启" :active-value="1"
								inactive-text="禁" :inactive-value="0"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户描述" prop="description">
							<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入用户描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(userDialogFormRef)" size="default">{{ state.dialog.submitTxt
					}}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { nextTick, reactive, ref } from 'vue';
import { useDeptApi } from "/@/api/dept/index";
import { useRoleApi } from "/@/api/role/index";
import { useUserApi } from "/@/api/user/index";
import { CascaderValue, ElMessage, FormInstance } from 'element-plus';

const deptApi = useDeptApi()
const roleApi = useRoleApi()
const userApi = useUserApi()

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 校验账户唯一性自定义校验规则（要定义在rules前）
const accountValidator = async (rule: any, value: any, callback: any) => {
	// 编辑的时候可不校验自己原有的账户名
	if (state.dialog.type === "edit" && value === state.check.account) {
		callback();
	}
	if (await checkAccount()) {
		callback();
	} else {
		callback(new Error('用户名已存在'));
	}
}
// 校验密码的合理性（6-14位、大小写字母、数字混合）
const passwordValidator = (rule: any, value: any, callback: any) => {
	if (state.dialog.type === "edit") {
		// 更新资料得时候可不修改密码
		callback();
	}
	if (value === "") {
		callback(new Error('请输入密码'));
	} else if (!/^.{6,14}$/.test(value)) {
		// 后期这些中文字都要改成国际化的占位
		callback(new Error('密码长度必须在6-14位之间'));
	} else if (!/[A-Z]/.test(value) || !/[a-z]/.test(value) || !/[0-9]/.test(value)) {
		callback(new Error('密码必须包含大写字母、小写字母和数字'));
	} else {
		callback();
	}
};

const phoneValidator = (rule: any, value: any, callback: any) => {

}

// 定义变量内容
const userDialogFormRef = ref<FormInstance>();
const state = reactive({
	ruleForm: {
		id: 0,
		account: '', // 账户名称
		username: '', // 用户昵称
		englishname: '', // 用户英文名
		role_id: 5, // 关联角色
		department: 0, // 部门
		phone: '', // 手机号
		email: '', // 邮箱
		gender: 1, // 性别
		password: '', // 账户密码
		status: 1, // 用户状态
		description: '', // 用户描述
		roles: [] as RowRoleType[]
	},
	deptData: [] as DeptTreeType[], // 部门数据
	roleData: [] as RowRoleType[], // 角色数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	rules: {
		account: [
			{ required: true, message: "请输入账户名", trigger: 'blur' },
			{ validator: accountValidator, trigger: 'blur' }
		],
		password: [
			{ validator: passwordValidator, trigger: 'blur' }
		],
		phone: [
			{ validator: phoneValidator, trigger: 'blur' }
		]
	},
	check: {
		account: '',
	}
});

// 打开弹窗
const openDialog = (type: string, row: RowUserType) => {
	getDeptData();
	getRoleData();
	// 清空表单，此项需加表单验证才能使用
	if (userDialogFormRef.value) {
		nextTick(() => {
			userDialogFormRef.value!.resetFields();
		});
	}
	state.dialog.type = type;
	if (type === 'edit') {
		state.ruleForm = JSON.parse(JSON.stringify(row));
		if (row.roles.length > 0) {
			state.ruleForm.role_id = (row.roles as any[])[0].id;
		} else {
			state.ruleForm.role_id = 5;
		}
		state.check.account = row.account;
		state.dialog.title = '修改用户';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '新增用户';
		state.dialog.submitTxt = '新 增';
		state.ruleForm = {} as RowUserType
	}
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (state.dialog.type === 'add') {
				await addUser().then(res => {
					ElMessage.success("新增成功");
				}).catch(err => {
					ElMessage.warning("新增失败");
				})

			} else {
				await updateUser().then(res => {
					ElMessage.success("修改成功");
				}).catch(err => {
					ElMessage.warning("修改失败");
				})
			}
			closeDialog();
			emit('refresh');
		} else {
			return;
		}
	})
};

// 新增用户
const addUser = () => {
	if (state.ruleForm.department) {
		state.ruleForm.department = (state.ruleForm.department as any)[(state.ruleForm.department as any).length - 1];
	} else {
		state.ruleForm.department = 0;
	}
	return userApi.addUser(state.ruleForm);
}
// 修改用户
const updateUser = () => {
	state.ruleForm.department = (state.ruleForm.department as any)[(state.ruleForm.department as any).length - 1]
	return userApi.updateUser(state.ruleForm);
}

// 初始化部门数据
const getDeptData = () => {
	deptApi.getDeptTree().then((res) => {
		state.deptData = res.result;
	})
};
// 部门变化
const deptChange = (value: CascaderValue) => {
	console.log(value)
}

// 初始化角色数据
const getRoleData = () => {
	roleApi.getAllRoles().then((res) => {
		state.roleData = res.result;
	})
};
const roleChange = (value: any) => {
}

// 校验账户请求接口
const checkAccount = async () => {
	return await userApi.checkAccount({ account: state.ruleForm.account }).then((res => {
		return res.result === "1" ? false : true;
	}))
}


// 暴露变量
defineExpose({
	openDialog,
});
</script>
